package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author tongchen
 * @create 2023-02-04 11:34
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user,HttpSession session ){
    //接收手机号
    log.info(user.getPhone().toString());
    String phone=user.getPhone();
    //判断手机号的合法性
   if( StringUtils.isNotEmpty(phone)){
       String code = ValidateCodeUtils.generateValidateCode(4).toString();
      // SMSUtils.sendMessage("瑞吉外卖", 404, phone, );
       //通过session缓存验证码\
       session.setAttribute(phone,code);
       return R.success("验证码发送成功");
   }
    //接受信息并生成验证码
    return R.error("验证码生成失败");
}
@PostMapping("/login")
    public R<User> login(@RequestBody Map map,HttpSession httpSession){
    log.info(map.toString());
    httpSession.setAttribute("13153382278", "3261");//模拟实现
    //获取手机号和验证码
    String phone = map.get("phone").toString();
    String code="3261";
    //String code = map.get("code").toString();//并没有通过后端（前端自动生成了，我们这里会产生空指针）
    //判断是否正确
    String attribute = httpSession.getAttribute(phone).toString();
    if(attribute.equals(code)){
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, phone);
        User user = userService.getOne(queryWrapper);
        if(user==null){
            //创建新的user
             user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            userService.save(user);
        }
       httpSession.setAttribute("user", user.getId());
        return R.success(user);
    }

    return R.error("登陆失败");
}
}
